﻿using Dlpad.Services;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model;

namespace Dlpad.Controllers
{
    //字典类型管理
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class DictTypeController : ControllerBase
    {
        private readonly IDictTypeService _dictTypeService;

        public DictTypeController(IDictTypeService dictTypeService)
        {
            _dictTypeService = dictTypeService;
        }

        /// <summary>
        /// 分页查询字典类型
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<PagedResultDto<DictTypeResponseDto>>> GetDictTypes([FromQuery] DictTypeQueryDto query)
        {
            var result = await _dictTypeService.GetDictTypesAsync(query);
            return Ok(result);
        }

        /// <summary>
        /// 根据ID获取字典类型
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<SysDictType>> GetDictType(long id)
        {
            var dictType = await _dictTypeService.GetDictTypeByIdAsync(id);
            if (dictType == null)
            {
                return NotFound();
            }
            return Ok(dictType);
        }

        /// <summary>
        /// 创建字典类型
        /// </summary>
        [HttpPost]
        public async Task<ActionResult> CreateDictType(SysDictType dictType)
        {
            // 检查字典类型是否唯一
            if (!await _dictTypeService.IsDictTypeUniqueAsync(dictType.DictType))
            {
                return BadRequest("字典类型已存在");
            }

            //设置创建和更新信息
            dictType.CreateBy = "admin"; //或从当前用户获取
            dictType.CreateTime = DateTime.Now;
            dictType.UpdateBy = "admin"; //或从当前用户获取
            dictType.UpdateTime = DateTime.Now;

            if (await _dictTypeService.CreateDictTypeAsync(dictType))
            {
                return CreatedAtAction(nameof(GetDictType), new { id = dictType.DictId }, dictType);
            }

            return BadRequest("创建失败");
        }

        /// <summary>
        /// 更新字典类型
        /// </summary>
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateDictType(long id, SysDictType dictType)
        {
            try
            {
                Console.WriteLine($"=== 开始更新字典类型 ===");
                Console.WriteLine($"URL ID: {id}, 请求体 DictId: {dictType.DictId}");
                Console.WriteLine($"请求数据: DictName={dictType.DictName}, DictType={dictType.DictType}, Status={dictType.Status}");

                if (id != dictType.DictId)
                {
                    Console.WriteLine($"ID不匹配: URL中的ID({id}) != 请求体中的DictId({dictType.DictId})");
                    return BadRequest("ID不匹配");
                }

                // 检查字典类型是否唯一
                Console.WriteLine($"检查字典类型唯一性: {dictType.DictType}, 排除ID: {id}");
                var isUnique = await _dictTypeService.IsDictTypeUniqueAsync(dictType.DictType, id);
                Console.WriteLine($"字典类型唯一性检查结果: {isUnique}");

                if (!isUnique)
                {
                    Console.WriteLine($"字典类型已存在: {dictType.DictType}");
                    return BadRequest("字典类型已存在");
                }

                Console.WriteLine($"获取现有字典类型: ID={id}");
                var existingDictType = await _dictTypeService.GetDictTypeByIdAsync(id);
                if (existingDictType == null)
                {
                    Console.WriteLine($"字典类型不存在: ID={id}");
                    return NotFound("字典类型不存在");
                }

                Console.WriteLine($"现有数据 - DictType: {existingDictType.DictType}, CreateBy: {existingDictType.CreateBy}");

                // 保留原有的创建信息
                dictType.CreateBy = existingDictType.CreateBy;
                dictType.CreateTime = existingDictType.CreateTime;

                Console.WriteLine($"调用更新服务...");
                var updateResult = await _dictTypeService.UpdateDictTypeAsync(dictType);
                Console.WriteLine($"更新服务返回: {updateResult}");

                if (updateResult)
                {
                    // 验证更新结果
                    var updated = await _dictTypeService.GetDictTypeByIdAsync(id);
                    Console.WriteLine($"更新验证 - DictType: {updated?.DictType}");
                    Console.WriteLine("=== 更新成功 ===");
                    return NoContent();
                }
                else
                {
                    Console.WriteLine("=== 更新服务返回失败 ===");
                    return BadRequest("更新失败：服务层返回false");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"=== 更新过程中发生异常 ===");
                Console.WriteLine($"异常类型: {ex.GetType().Name}");
                Console.WriteLine($"异常消息: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");

                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                }

                return BadRequest($"更新失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除字典类型
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteDictType(long id)
        {
            if (await _dictTypeService.DeleteDictTypeAsync(id))
            {
                return NoContent();
            }

            return BadRequest("删除失败");
        }
    }
}
